package com.tanhua.timedTask;

import cn.hutool.core.date.DateUtil;
import com.tanhua.domain.AnalysisByDay;
import com.tanhua.mapper.AnalysisByDayMapper;
import com.tanhua.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component //定时任务
public class MyTask {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    //    七子表达式 :     秒 分 时 天 月 周  *年(省略)
    //@Scheduled(cron = "0/5 *  *  *  * ?") //每5秒执行一次
    @Scheduled(cron = "00 45 21 * * ?") // 每天 19点 30分 执行一次
    public void analysis() {

        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(time);

        //todo: 每天 ? 点 去tb_log表查出统计的数据 放入tb_analysis_by_day表中

        //获取今天日期
        String today = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        //获取昨天日期
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //查询注册数 type = 0102
        Integer numRegistered = logMapper.findNumRegistered(today, "0102");
        //查询登录数 type = 0101
        Integer numLogin = logMapper.findNumLogin(today, "0101");

        //查询活跃数
        Integer numActive=logMapper.findNumActive(today);

        //查询留存数
        Integer numRetention1d=logMapper.findNumRetention1d(yesterday,today);


        //5 封装给统计表（实体）
        AnalysisByDay analysisByDay = new AnalysisByDay();
        analysisByDay.setNumRegistered(numRegistered);
        analysisByDay.setNumLogin(numLogin);
        analysisByDay.setNumActive(numActive);
        analysisByDay.setNumRetention1d(numRetention1d);
        analysisByDay.setRecordDate(DateUtil.parseDate(today));
        analysisByDay.setCreated(new Date());
        analysisByDay.setUpdated(new Date());

        //6 将实体插入到统计表中tb_analysis_by_day
        analysisByDayMapper.insert(analysisByDay);

        System.out.println("统计完毕...");
    }

}
